package cn.lili.modules.lucene;

import cn.lili.modules.search.entity.dos.EsGoodsAttribute;
import cn.lili.modules.search.entity.dos.EsGoodsIndex;
import org.apache.lucene.document.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 15:16 2025/7/9
 */
public class LuceneUtil {

    public static Document convertToDocument(EsGoodsIndex esGoodsIndex) {
        Document doc = new Document();

        // ID字段（不分词）
        doc.add(new StringField("id", esGoodsIndex.getId(), Field.Store.YES));

        // GOODS_ID字段（不分词）
        doc.add(new StringField("goodsId", esGoodsIndex.getGoodsId(), Field.Store.YES));

        // 商品名称（需要分词搜索）
        doc.add(new TextField("goodsName", esGoodsIndex.getGoodsName(), Field.Store.YES));

        // 商品sn
        if (esGoodsIndex.getSn() != null) {
            doc.add(new StringField("sn", esGoodsIndex.getSn(), Field.Store.YES));
        }

        // GOODS_ID字段（不分词）
        doc.add(new StringField("storeId", esGoodsIndex.getStoreId(), Field.Store.YES));

        doc.add(new StringField("storeName", esGoodsIndex.getStoreName(), Field.Store.YES));

        // 小图
        if (esGoodsIndex.getSmall() != null) {
            doc.add(new StringField("small", esGoodsIndex.getSmall(), Field.Store.YES));
        }
        if (esGoodsIndex.getThumbnail() != null) {
            doc.add(new StringField("thumbnail", esGoodsIndex.getThumbnail(), Field.Store.YES));
        }


        // 品牌id
        if (esGoodsIndex.getBrandId() != null) {
            // 品牌ID（不分词）
            doc.add(new StringField("brandId", esGoodsIndex.getBrandId(), Field.Store.YES));
        }
        if (esGoodsIndex.getBrandName() != null){
            // 品牌名称
            doc.add(new TextField("brandName", esGoodsIndex.getBrandName(), Field.Store.YES));
            // 用于聚合 (DocValues)
            doc.add(new StringField("brandAgg", esGoodsIndex.getBrandName(), Field.Store.YES));
        }

        if (esGoodsIndex.getBrandUrl() != null ) {
            // 品牌图片url
            doc.add(new StringField("brandUrl", esGoodsIndex.getBrandUrl(), Field.Store.YES));
        }

        // 销量（数值类型需特殊处理）
        doc.add(new DoublePoint("buyCountIndex", esGoodsIndex.getBuyCount()));
        doc.add(new StoredField("buyCount", esGoodsIndex.getBuyCount())); // 同时存储原始值

        if (esGoodsIndex.getCategoryPath() != null) {
            doc.add(new StringField("categoryPath", esGoodsIndex.getCategoryPath(), Field.Store.YES));
            // 为每个分类ID添加独立的可聚合字段
            String[] categoryIds = esGoodsIndex.getCategoryPath().split(",");
            for (String catId : categoryIds) {
                doc.add(new StringField("catAgg", catId, Field.Store.YES));
            }
        }
        if (esGoodsIndex.getCategoryNamePath() != null) {
            doc.add(new StringField("categoryNamePath", esGoodsIndex.getCategoryNamePath(), Field.Store.YES));
        }
        if (esGoodsIndex.getStoreCategoryPath() != null) {
            doc.add(new StringField("storeCategoryPath", esGoodsIndex.getStoreCategoryPath(), Field.Store.YES));
        }


        // 价格（数值类型需特殊处理）
        doc.add(new DoublePoint("priceIndex", esGoodsIndex.getPrice()));
        doc.add(new StoredField("price", esGoodsIndex.getPrice())); // 同时存储原始值

        // 促销价格（数值类型需特殊处理）
        if (esGoodsIndex.getPromotionPrice() != null) {
            doc.add(new DoublePoint("promotionPriceIndex", esGoodsIndex.getPromotionPrice()));
            doc.add(new StoredField("promotionPrice", esGoodsIndex.getPromotionPrice())); // 同时存储原始值
        }

        // 所需积分
        if (esGoodsIndex.getPoint() != null) {
            doc.add(new StoredField("point", esGoodsIndex.getPoint()));
        }

        if (esGoodsIndex.getCommentNum() != null) {
            // 评价数量（数值类型需特殊处理）
            doc.add(new DoublePoint("commentNumIndex", esGoodsIndex.getCommentNum()));
            doc.add(new StoredField("commentNum", esGoodsIndex.getCommentNum())); // 同时存储原始值
        }
        if (esGoodsIndex.getHighPraiseNum() != null) {
            // 好评数量
            doc.add(new StoredField("highPraiseNum", esGoodsIndex.getHighPraiseNum()));
        }
        if (esGoodsIndex.getGrade() != null) {
            doc.add(new StoredField("grade", esGoodsIndex.getGrade()));
        }

        // 详情
        // doc.add(new StoredField("intro", esGoodsIndex.getIntro()));

        // 是否自营 相同字段名称
        doc.add(new IntPoint("selfOperated", esGoodsIndex.getSelfOperated() ? 1 : 0));
        doc.add(new StoredField("selfOperated", esGoodsIndex.getSelfOperated() ? 1 : 0)); // 同时存储原始值

        // 是否推荐商品 相同字段名称
        doc.add(new IntPoint("recommend", esGoodsIndex.getRecommend() ? 1 : 0));
        doc.add(new StoredField("recommend", esGoodsIndex.getRecommend() ? 1 : 0)); // 同时存储原始值

        // 上架状态（不分词）
        doc.add(new StringField("marketEnable", esGoodsIndex.getMarketEnable(), Field.Store.YES));

        // 分类列表（处理嵌套数据）
//        for(Category cat : goods.getCategories()) {
//            doc.add(new StringField("category", cat.getId(), Field.Store.YES));
//        }

        // 时间类型示例
        doc.add(new LongPoint("releaseTime", esGoodsIndex.getReleaseTime()));

        // 属性存储容器（按属性名分组）
        Map<String, Set<String>> attributeMap = new HashMap<>();

        if (esGoodsIndex.getAttrList() != null) {
            for (EsGoodsAttribute attr : esGoodsIndex.getAttrList()) {
                String name = attr.getName() != null ? attr.getName() : "";
                String value = attr.getValue() != null ? attr.getValue() : "";
                if (name.isEmpty() || value.isEmpty()) {
                    continue; // 跳过空属性
                }
                // 1. 按属性名分组存储值
                attributeMap.computeIfAbsent(name, k -> new HashSet<>())
                        .add(value);

                // 2. 保留原始组合字段（兼容单值查询）
                doc.add(new StringField("attr", name + "::" + value, Field.Store.YES));

                // 3. 可聚合字段 (按属性名分组)
                doc.add(new StringField("attrValueAgg", name + "::" + value, Field.Store.YES)); // 确保Store.YES

                // 同时添加分类聚合字段
                if (attr.getType() == 1) { // 参数类型
                    doc.add(new StringField("paramNameAgg", name, Field.Store.NO));
                }
            }

            // 3. 为每个属性创建多值字段
            for (Map.Entry<String, Set<String>> entry : attributeMap.entrySet()) {
                String attrName = entry.getKey();
                Set<String> values = entry.getValue();
                if (values.isEmpty()) {
                    continue; // 跳过空属性
                }

                // 创建规范化的字段名（避免特殊字符）
                String fieldName = "attr_" + attrName.replaceAll("[^a-zA-Z0-9]", "_");

                // 添加每个属性值
                for (String val : values) {
                    doc.add(new StringField(fieldName, val, Field.Store.YES));
                }
            }
        }

        return doc;
    }

    public static EsGoodsIndex convertDocumentToEsGoodsIndex(Document doc) {
        EsGoodsIndex index = new EsGoodsIndex();

        // 基础字段
        index.setId(doc.get("id"));
        index.setGoodsId(doc.get("goodsId"));
        index.setGoodsName(doc.get("goodsName"));
        index.setSn(doc.get("sn"));
        index.setStoreId(doc.get("storeId"));
        index.setStoreName(doc.get("storeName"));
        index.setCategoryNamePath(doc.get("categoryNamePath"));
        index.setCategoryPath(doc.get("categoryPath"));
        index.setStoreCategoryPath(doc.get("storeCategoryPath"));
        index.setStoreCategoryNamePath(doc.get("storeCategoryNamePath"));
        if (doc.get("commentNum") != null) {
            index.setCommentNum(Integer.parseInt(doc.get("commentNum")));
        }


        // 数值字段
        index.setBuyCount(Integer.parseInt(doc.get("buyCount")));
        index.setPrice(Double.parseDouble(doc.get("price")));

        // 布尔字段
        index.setSelfOperated("1".equals(doc.get("selfOperated")));
        index.setRecommend("1".equals(doc.get("recommend")));

        // 其他字段转换...
        index.setSmall(doc.get("small"));
        index.setThumbnail(doc.get("thumbnail"));
        //index.setSkuSource(doc.get("skuSource"));

        return index;
    }

}
